import React from 'react';
import { Button, Modal, message } from 'antd';
import { inject, observer } from 'mobx-react';
import { WeaTop, WeaTab, WeaLeftRightLayout, WeaRightMenu, WeaPopoverHrm, WeaTools, WeaErrorPage, WeaDialog, WeaAlertPage } from 'ecCom';
import { observable, action, toJS } from 'mobx';
import { WeaTableNew } from 'comsMobx';
import CptInventoryPlanNew from '../form/CptInventoryPlanNew';
import { Condition, getAdButtons } from './ListCondition';// inventory目录下单独用的
import PlanInfoTab from './PlanInfoTab';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

const WeaTable = WeaTableNew.WeaTable;

@inject('cptInventoryStore')
@observer
class CptInventoryPlanList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // addTitle: getLabel(384628,"新建盘点计划"),
      // editTitle: getLabel(384630,"编辑盘点计划")
    };
  }
  doInit(props) {
    const { location, cptInventoryStore } = props;
    const { appendBaseParams, doSearch, initDatas, initPlanmainDatas, initPlanListCptDatas } = cptInventoryStore;
    initDatas();// 高级查询
    doSearch();// 查找盘点计划
    initPlanmainDatas();
    initPlanListCptDatas();
  }
  componentDidMount() {
    this.doInit(this.props);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      const { cptInventoryStore } = this.props;
      cptInventoryStore.clearStatus();
      this.doInit(nextProps);
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    return true;
  }
  componentWillUnmount() {
    const { cptInventoryStore } = this.props;
    cptInventoryStore.clearStatus();
  }
  render() {
    const { cptInventoryStore } = this.props;
    const { loading, dataKey, tableStore, searchParams, form, doEdit, doAdd, doPlanVisible, addVisible,
      setVisiable, addform, addformCondition, editform, editformCondition, fieldsel, casesel, setPlanrule, editVisible, showSearchAd, isright } = cptInventoryStore;
    const formParams = form.getFormParams() || {};
    const tableNow = this.getCurrentTable();
    const loadingTable = tableNow.loading;
    const addTitle = getLabel(384636, '新建盘点计划');
    const editTitle = getLabel(384630, '编辑盘点计划');
    const addButtons = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cqamth@save`} type="primary" disabled={doPlanVisible} onClick={() => doAdd()} >{getLabel(86, '保存')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8374wp@close`} type="ghost" disabled={doPlanVisible} onClick={() => this.closeAllDialog()} >{getLabel(201, '取消')}</Button>),
    ];
    const editButtons = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@94fkcp@save`} type="primary" disabled={doPlanVisible} onClick={() => doEdit()} >{getLabel(86, '保存')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yarlwx@close`} type="ghost" disabled={doPlanVisible} onClick={() => this.closeAllDialog()} >{getLabel(201, '取消')}</Button>),
    ];

    if (!isright) {
      return (
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@aieh10`}>
          <div style={{ color: '#000' }}>
            {getLabel(2012, '对不起，您暂时没有权限！')}
          </div>
        </WeaAlertPage>
      );
    }

    return (
      <div>
        <WeaTop
          ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@fhq4t4`}
          title={getLabel('383832', '盘点计划')}
          loading={loading || loadingTable}
          icon={<i className="icon-coms-fa" />}
          iconBgcolor="#f14a2d"
          buttons={this.getTopButtons()}
          buttonSpace={10}
          showDropIcon
          dropMenuDatas={this.getRightMenu()}
        >

          <WeaTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@irrt9m`} // 高级搜素
            buttonsAd={getAdButtons(cptInventoryStore)}
            searchType={['base', 'advanced']}
            showSearchAd={showSearchAd}
            searchsBaseValue={formParams.flowTitle}
            setShowSearchAd={bool => cptInventoryStore.setShowSearchAd(bool)}
            hideSearchAd={() => cptInventoryStore.setShowSearchAd(false)}
            onSearch={(v) => { cptInventoryStore.doSearch(); }}
            showSearchDrop={false}
            searchsAd={
              <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@wrisst`} listStore={cptInventoryStore} form={form} onEnterSearch={this.onEnterSearch} /></div>
            }
            onSearchChange={(v) => { cptInventoryStore.appendFormFields({ flowTitle: v }); }}
          />

          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@2egj41`} datas={this.getRightMenu()}>
            <WeaTable
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@g4nnbq`}
              sessionkey={dataKey}
              comsWeaTableStore={tableStore}
              hasOrder
              needScroll
              onOperatesClick={this.onOperatesClick.bind(this)}
              getColumns={c => this.reRenderColumns(c)}
            />

            <PlanInfoTab ecId={`${this && this.props && this.props.ecId || ''}_PlanInfoTab@4h9na8`} contentStore={cptInventoryStore} />
          </WeaRightMenu>
        </WeaTop>

        <WeaDialog
          ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@7nlprh`} // 新建盘点计划
          title={addTitle}
          visible={addVisible}
          onCancel={() => { setVisiable(false, 1); }}
          icon="icon-coms-fa"
          iconBgcolor="#f14a2d"
          buttons={addButtons}
          style={{ width: 600, height: 450 }}
        >
          <CptInventoryPlanNew ecId={`${this && this.props && this.props.ecId || ''}_CptInventoryPlanNew@6ijb8p`} form={addform} formcondition={addformCondition} fieldsel={fieldsel} casesel={casesel} setPlanrule={setPlanrule} method="add" />
        </WeaDialog>

        <WeaDialog
          ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@r6o6qd`} // 编辑盘点计划
          title={editTitle}
          visible={editVisible}
          onCancel={() => { setVisiable(false, 2); }}
          icon="icon-coms-fa"
          iconBgcolor="#f14a2d"
          buttons={editButtons}
          style={{ width: 550, height: 400 }}
        >
          <CptInventoryPlanNew ecId={`${this && this.props && this.props.ecId || ''}_CptInventoryPlanNew@vccu6z`} form={editform} formcondition={editformCondition} fieldsel={fieldsel} casesel={casesel} setPlanrule={setPlanrule} method="edit" />
        </WeaDialog>

      </div>
    );
  }

  reRenderColumns(columns) {
    const { cptInventoryStore } = this.props;
    const divStyle = {
      cursor: 'pointer',
    };
    columns.forEach((c) => {
      if (c.dataIndex == 'mark' || c.dataIndex == 'name') {
        c.render = function (text, record) {
          const valueSpan = record[`${c.dataIndex}span`] !== undefined ? record[`${c.dataIndex}span`] : record[c.dataIndex];
          return (<span
            style={divStyle}
            onClick={() => {
              cptInventoryStore.setSelectId({ selectid: record.randomFieldId });
              cptInventoryStore.handleDialog(true, { id: record.randomFieldId, name: record.name }, 0);
            }}
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />);
        };
      }
    });
    return columns;
  }

    onOperatesClick = (record, index, operate, flag, argumentString) => {
      const { cptInventoryStore } = this.props;
      const { doSearch, doDelete, setSelectId, setVisiable, startInventory, copyInventory, finishInventory } = cptInventoryStore;

      const _href = operate && operate.href ? operate.href : '';
      let fn = _href.replace('javascript:', '');
      fn = fn.substring(0, fn.indexOf('('));
      const that = this;
      if (fn != '') {
        if (fn == 'onEdit') {
          setSelectId({ selectid: record.randomFieldId });
          setVisiable(true, 2);
          cptInventoryStore.getEditPlanForm({
            id: record.randomFieldId,
          });
        } else if (fn == 'onDel') {
          Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(83600, '您确认要删除吗?'),
            onOk() {
              doDelete({ id: record.randomFieldId });
            },
            onCancel() { },
          });
        } else if (fn == 'onViewDetail') {
          setSelectId({ selectid: record.randomFieldId });
          cptInventoryStore.handleDialog(true, { id: record.randomFieldId, name: record.name }, 0);
        } else if (fn == 'startInventory') {
          Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel('384631', '开始之后盘点计划将无法修改,是否开始盘点?'),
            onOk() {
              startInventory({ id: record.randomFieldId });
            },
            onCancel() { },
          });
        } else if (fn == 'copyInventory') {
          Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel('384632', '整个盘点计划将会被复制,是否继续?'),
            onOk() {
              copyInventory({ id: record.randomFieldId });
            },
            onCancel() { },
          });
        } else if (fn == 'finishInventory') {
          Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel('384633', '是否确定强制完成?'),
            onOk() {
              finishInventory({ id: record.randomFieldId });
            },
            onCancel() { },
          });
        }
      }
    }
    getCurrentTable() {
      const { cptInventoryStore } = this.props;
      const { dataKey, tableStore } = cptInventoryStore;
      const tableKey = dataKey ? dataKey.split('_')[0] : 'init';
      return tableKey;
    }

    getTopButtons() {
      const { setVisiable, canAddPlan } = this.props.cptInventoryStore;
      const tableStore = this.props.cptInventoryStore.tableStore;
      const selectedLen = tableStore.selectedRowKeys.length;
      const btns = [];
      btns.push(<Button
        ecId={`${this && this.props && this.props.ecId || ''}_Button@ygdzur@add`}
        type="primary"
        disabled={!canAddPlan}
        onClick={() => {
          this.props.cptInventoryStore.getAddPlanForm(),
          setVisiable(true, 1);
        }
        }
      >{getLabel(82, '新建')}</Button>);
      btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xog7gh@delete`} type="primary" disabled={!selectedLen > 0} onClick={this.batchDeleteClick}>{getLabel(32136, '批量删除')}</Button>);
      return btns;
    }
    getRightMenu() {
      const { cptInventoryStore } = this.props;
      const { tableStore, setVisiable, canAddPlan } = cptInventoryStore;
      const tableNow = this.getCurrentTable();
      const selectedLen = tableStore.selectedRowKeys.length;
      const totalLen = tableNow.count;
      const btns = [];
      if (canAddPlan) {
        btns.push({
          key: 'create',
          icon: <i className="icon-coms-New-Flow" />,
          content: getLabel(82, '新建'),
          onClick: (key) => {
            cptInventoryStore.getAddPlanForm(),
            setVisiable(true, 1);
          },
        });
      }
      btns.push({
        key: 'batchDelete',
        disabled: selectedLen == 0,
        icon: <i className="icon-coms-delete" />,
        content: getLabel(32136, '批量删除'),
        onClick: (key) => {
          this.batchDeleteClick();
        },
      });

      return btns;
    }
    batchDeleteClick = () => { // 批量删除
      const { cptInventoryStore: { tableStore, doBatchDelete } } = this.props;
      const { selectedRowKeys } = tableStore;// 得到选中数据的id

      const count = toJS(selectedRowKeys).length;
      Modal.confirm({
        title: getLabel(15172, '系统提示'),
        content: getLabel(83692, '您确认要批量处理选中的记录吗？'),
        onOk() {
          doBatchDelete({ ids: selectedRowKeys });
        },
        onCancel() { },
      });
    }

    closeAllDialog() {
      const { setVisiable } = this.props.cptInventoryStore;
      setVisiable(false, 1);
      setVisiable(false, 2);
    }

    onEnterSearch = () =>{
      const { cptInventoryStore } = this.props;
      cptInventoryStore.doSearch();
      cptInventoryStore.setShowSearchAd(false);
    }

}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@nvryao`} msg={props.error ? props.error : getLabel(383324, '对不起，该页面异常，请联系管理员')} />,
  { error: '' },
)(CptInventoryPlanList);
